package datacollectionator;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;

public abstract class Logger implements AutoCloseable {
	private static boolean isEnabled;
	
	private static String fileName;
	
	static {
		isEnabled = false;
	}
	
	public static boolean isEnabled() {
		return isEnabled;
	}
	
	public static void setEnabled(boolean isEnabled) {
		Logger.isEnabled = isEnabled;
	}
	
	public static Logger instance() throws IOException {
		if (isEnabled) {
			return new EnabledLogger(fileName);
		} else {
			return new DisabledLogger();
		}
	}
	
	public static String getLogFileName() {
		return fileName;
	}
	
	public static void setLogFileName(String fileName) {
		Logger.fileName = fileName;
	}
	
	public static void clearFile() throws IOException {
		File file = new File(fileName);
		if (file.exists()) {
			RandomAccessFile f = new RandomAccessFile(file, "rw");
			f.setLength(0);
			f.close();
		}
	}
	
	
	
	public abstract void write(String text) throws IOException;
	
	public abstract void newLine() throws IOException;

	
	
	private static class EnabledLogger extends Logger implements AutoCloseable {
		private BufferedWriter bw;
		
		public EnabledLogger(String fileName) throws IOException {
			assert(fileName != null);
			
			bw = new BufferedWriter(new FileWriter(fileName, true));
		}

		@Override
		public void write(String text) throws IOException {
			bw.write(text);
		}

		@Override
		public void newLine() throws IOException {
			bw.newLine();
		}

		@Override
		public void close() throws IOException {
			bw.close();
		}
	}
	
	private static class DisabledLogger extends Logger {
		@Override
		public void write(String text) { /* do nothing */ }

		@Override
		public void newLine() throws IOException { /* do nothing */ }

		@Override
		public void close() { /* do nothing */ }
	}
}
